import logging
from functools import wraps
from util.utils import mkdirs

class track_log:
    def __init__(self, title):
        logging.basicConfig(# format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s',
                        format='%(message)s',
                        level=logging.INFO,
                        filename=title,
                        filemode='w')
        self.tl = logging.getLogger(title)
        
    def get_logger(self):
        return self.tl

class Recorder(object):
    def __init__(self, header=None, recorder_file="out.csv", mode='a'):
        """
        :header: 表头，用逗号隔开
        # :formats: 数据格式，如两个单元格，formats="{}, {}"
        """
        if mode == "a":
            self.header = None
        else:
            self.header = header
        self.recorder_file = recorder_file

        mkdirs(self.recorder_file)
        if header is not None:
            self.build_header(mode)

    def build_header(self, mode):
        self.write_to_file(self.header, mode)
    
    def write_to_file(self, s, mode='a'):
        with open(self.recorder_file, mode) as opended_file:
            opended_file.write(s + "\n")

    def record_one(self, s):
        self.write_to_file(s)
        self.notify()

    def __call__(self, func):
        @wraps(func)
        def wrapped_function(*args, **kwargs):
            formats = f"{'{},'*len(args)}".format(*args)
            recoder_string = formats[0:-1]
            self.write_to_file(recoder_string)
            self.notify()
            return func(*args, **kwargs)
        return wrapped_function
                
    def notify(self):
        # print(s)
        pass

if __name__ == "__main__":
    # test
    tl = track_log().get_logger()
    tl.info(f"3, 5")
    tl.info(f"5, 6")